package controller.SaleTable;

import entity.MsgResult;
import entity.goods;
import entity.sale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.AddSaleService;
import service.SelectGoodsByIdService;
import service.UpdateGoodsService;

import java.util.Date;

@Controller
public class AddSaleController{
    @Autowired
    private AddSaleService addSaleService;

    @Autowired
    private UpdateGoodsService updateGoodsService;

    @Autowired
    private SelectGoodsByIdService selectGoodsByIdService;

    @RequestMapping("/addSale")
    @ResponseBody
    public MsgResult addSale(sale sale){
        MsgResult msgResult = new MsgResult();
        Date currDate = new Date();
        //获取当前时间
        sale.setSaleDate(currDate);
        //根据id查询要更新数据的商品
        goods good = selectGoodsByIdService.selectGoodsById(sale.getGoodsId());
        //创建对象
        goods goods = new goods();
        goods.setGoodsId(sale.getGoodsId());
        //库存更新
        int newNum = (int) (good.getStockNum() - sale.getNum());
        if(newNum < 0){
            msgResult.setFlag(0);
            msgResult.setMsg("库存不够");
            return msgResult;
        }
        goods.setStockNum((long) newNum);
        goods.setNumUpdateDate(currDate);
        updateGoodsService.updateGoods(goods);
        boolean b = addSaleService.addSale(sale);
        if(b){
            msgResult.setFlag(1);
            msgResult.setMsg("销售成功");
            return msgResult;
        }
        msgResult.setFlag(1);
        msgResult.setMsg("销售失败");
        return msgResult;
    }
}
